<script>
import {changeStatus, deleteSound, getPageList, uploadSound} from "@/api/aihuman/humanAssets/soundType";
import HuilanUploader from "@/components/uploader/index.vue";
import AddSound from "@/views/aihuman/HumanAssets/soundType/AddSound.vue";
import {mapGetters} from "vuex";

export default {
  name: "SoundTypeList",
  components: {AddSound, HuilanUploader},
  data() {
    //检验声音id
    var checkType = (rule, value, callback) => {
      // var inputType = /[^\w]/g
      var inputReg = /[a-zA-Z0-9-_]/g;
      if (!inputReg.test(value)) {
        callback(new Error('声音id由数字、英文、短划线、下划线组成'))
      } else {
        callback()
      }
    };
    return {
      soundGroupId: '',
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      form: {},
      audioData: '',
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100],
      },
      tableData: [],
      tableOptions: {
        //新增按钮
        addBtn: false,
        header: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        stripe: false,
        selection: true,
        tip: false,
        height: 'auto',
        // simplePage: false,
        searchMenuSpan: 8,
        border: true,
        index: true,
        indexWidth: 60,
        indexLabel: "序号",
        menuWidth: 252,
        align: "left",
        menuAlign: "left",
        dialogWidth: "40%",
        dialogClickModal: false,
        dialogType: "drawer",
        span: 24,
        dialogCustomClass: "huilan-drawer-form",
        emptyText: this.$t('aicosCommon.notData'),
        column: [
          {
            label: "声音名称",
            prop: "soundTypeName",
            minWidth: 200,
            // search: true,
            searchSpan: 8,
            overHidden: true,
            rules: [
              {
                required: true,
                message: '请输入声音名称',
                trigger: 'blur'
              },
              {min: 1, max: 30, message: '长度不可超过30个字符', trigger: 'blur'}
            ]
          },
          {
            label: "声音id",
            prop: "soundTypeCode",
            minWidth: 200,
            // search: true,
            searchSpan: 8,
            overHidden: true,
            rules: [
              {required: true, message: '请输入声音id', trigger: 'blur'},
              {min: 1, max: 50, message: '长度不可超过50个字符', trigger: 'blur'},
              {required: true, validator: checkType, trigger: 'blur'}
            ]
          },
          {
            label: "状态",
            prop: "status",
            type: "switch",
            dicData: [
              {
                label: "启用",
                value: 0,
              },
              {
                label: "禁用",
                value: 1,
              },
            ],
          },
          {
            label: "创建时间",
            minWidth: 150,
            prop: "createTime",
            overHidden: true,
            display: false
          },
          {
            label: "标签",
            prop: "soundTypeTag",
            hide: true
          },
          {
            label: "预览声音",
            prop: "soundVideoLink",
            hide: true,
            rules: [
              {required: true, message: '请上传声音文件', trigger: 'blur'},
            ]
          },
        ],
      },
      searchForm: {
        soundTypeName: '',
        soundTypeCode: ''
      },
      searchFieldList: [
        {
          prop: 'soundTypeName',
          placeholder: '请输入声音名称'
        },
        {
          prop: 'soundTypeCode',
          placeholder: '请输入声音id'
        }
      ],
      selectedList: []
    }
  },
  created() {
    // this.getList()
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission[`assets-sound-add`], false),
        editBtn: this.vaildData(this.permission[`assets-sound-edit`], false),
        enableBtn: this.vaildData(this.permission['assets-sound-status'], false),
        deleteBtn: this.vaildData(this.permission['assets-sound-delete'], false),
      }
    }
  },
  methods: {
    // handleClose(tag) {
    //   this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    // },
    //
    // showInput() {
    //   this.inputVisible = true;
    //   this.$nextTick(_ => {
    //     this.$refs.saveTagInput.$refs.input.focus();
    //   });
    // },
    //
    // handleInputConfirm() {
    //   let inputValue = this.inputValue;
    //   if (inputValue) {
    //     this.dynamicTags.push(inputValue);
    //   }
    //   this.inputVisible = false;
    //   this.inputValue = '';
    // },
    handleAdd() {
      // this.$refs.listRef.rowAdd()
      this.$refs.soundRef.open('add', this.soundGroupId);
    },
    currentChange(current) {
      this.page.currentPage = current
      this.getList()
    },
    sizeChange(size) {
      this.page.pageSize = size
      this.getList()
    },
    configColumn() {
      this.$refs.listRef.$refs.dialogColumn.columnBox = true;
    },
    searchFn() {
      this.page.currentPage = 1
      this.getList()
    },
    getList() {
      this.$nextTick(async () => {
        let params = {
          soundGroupId: this.soundGroupId,
          ...this.searchForm,
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize
        }
        const {data} = await getPageList(params)
        this.tableData = data.data.records
        this.page.total = data.data.total
      })
    },
    selectionChange(selection) {
      this.selectedList = selection
    },
    async batchRemove() {
      if (this.selectedList.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择需要处理的数据",
        });
        return false
      }

      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let ids = this.selectedList.map(item => item.id)

        let params = {
          ids: ids.join(",")
        }
        const {data} = await deleteSound(params)
        this.$message({
          type: 'success',
          message: data.msg
        })
        this.getList()
        this.selectedList= []
      });

    },
    removeSound(row) {
      this.selectedList.push(row)
      this.batchRemove()
    },
    async toggleAction(row) {
      const {data} = await changeStatus({id: row.id, status: row.status ^ 1})
      console.log(data);
      this.$message.success(data.msg)
      this.getList()
    },
    previewRow(row) {
      this.$refs.soundRef.open('preview', this.soundGroupId, row)
    },
    editRow(row) {
      this.$refs.soundRef.open('edit', this.soundGroupId, row)
    },
    // async uploadAudio(file) {
    //   console.log(file);
    //   let formData = new FormData()
    //   formData.append('file', file.file)
    //   formData.append('fromSystemName', 'aimeta')
    //
    //   const {data} = await uploadSound(formData)
    //   this.audioData = data.data.url
    //   this.$refs.soundAudio.load()
    // },
    // saveSound(form, done, loading) {
    //   console.log(form, done, loading);
    // }
  }
}
</script>

<template>
  <div style="padding: 5px 30px 0">
    <HuilanBasicToolbar style="margin-top: 0">
      <el-button v-if="permissionList.addBtn" type="success" size="small" @click="handleAdd">{{
          $t("aicosCommon.addBtn")
        }}
      </el-button>
      <el-button v-if="permissionList.deleteBtn" type="primary" size="small" @click="batchRemove">
        批量删除
      </el-button>
    </HuilanBasicToolbar>

    <HuilanBasicSearchbar :model="searchForm" :fields="searchFieldList" @search="searchFn" @reset="getList">
      <template v-slot:appendTool>
        <el-button type="default" @click="configColumn"><i class="el-icon-s-operation"></i></el-button>
      </template>
    </HuilanBasicSearchbar>
    <avue-crud
      ref="listRef"
      v-model="form"
      :option="tableOptions"
      :page.sync="page"
      :data="tableData"
      @current-change="currentChange"
      @size-change="sizeChange"
      @row-save="saveSound"
      @selection-change="selectionChange"
    >
      <template slot-scope="scope" slot="menu">
        <el-button type="text" @click="previewRow(scope.row)">查看</el-button>
        <el-button v-if="permissionList.editBtn" type="text" @click="editRow(scope.row)">编辑</el-button>
        <el-button v-if="permissionList.enableBtn" type="text" @click="toggleAction(scope.row)">
          {{ scope.row.status === 0 ? '停用' : '启用' }}
        </el-button>
        <el-button v-if="permissionList.deleteBtn" type="text" @click="removeSound(scope.row)">删除</el-button>
      </template>
      <!--      <template slot="soundTypeTagForm" slot-scope="{type, disabled}">
              <el-tag
                :key="tag"
                v-for="tag in dynamicTags"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 标签</el-button>
            </template>-->

      <!--      <template slot="soundVideoLinkForm" slot-scope="{type, disabled}">
              <el-upload
                class="upload-demo"
                :http-request="uploadAudio"
                accept=".mp3,.wav"
                :show-file-list="false"
                drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传mp4/wav文件</div>
              </el-upload>

              <div v-if="audioData">
                <audio ref="soundAudio" :src="'https://ai3d.huilan.com/' + audioData" controls/>
              </div>
            </template>-->
    </avue-crud>

    <add-sound
      ref="soundRef"
      @save="getList"
    />
  </div>
</template>

<style scoped lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
